/****************************************************************************
**
** Copyright (C) 2009-2010 Mist Poryvaev.
** All rights reserved.
** Contact: Mist Poryvaev (mist.poryvaev@gmail.com)
**
** This file is part of the RailWorm project.
**
****************************************************************************/

#include "queryform.h"
#include "ui_queryform.h"
#include "parsetraindata.h"
#include "suggestcompletion.h"
#include "connectrzd.h"

QSettings QueryFormSettings("railworm.ini", QSettings::IniFormat);

QueryForm * QueryForm::g_Instance = 0;

QueryForm * QueryForm::i() {
	if (g_Instance == 0) {
		g_Instance = new QueryForm();
	}
	return g_Instance;
}

QueryForm::QueryForm(QWidget *parent) : QWidget(parent), m_ui(new Ui::QueryForm) {
    m_ui->setupUi(this);
	m_ui->formLayout->setSizeConstraint(QLayout::SetFixedSize);

	m_ui->FromEdit->setText(tr("петербург"));
	m_ui->ToEdit->setText(tr("москва"));
	m_ui->DateTimeEditStart->setMinimumDate(QDate::currentDate());
	m_ui->DateTimeEditStart->setMaximumDate(QDate::currentDate().addDays(44));
	m_ui->DateTimeEditStart->setDate(QDate::currentDate().addDays(1));
	m_ui->DateTimeEditEnd->setMinimumDate(QDate::currentDate());
	m_ui->DateTimeEditEnd->setMaximumDate(QDate::currentDate().addDays(44));
	m_ui->DateTimeEditEnd->setDate(QDate::currentDate().addDays(1));

	m_ui->FromEdit->setText(QueryFormSettings.value("QueryForm/From", tr("Петербург")).toString());
	m_ui->ToEdit->setText(QueryFormSettings.value("QueryForm/To", tr("Москва")).toString());

	connect(m_ui->FromEdit, SIGNAL(textEdited(QString)), this, SLOT(OnSuggestSrc(QString)));
	connect(m_ui->ToEdit, SIGNAL(textEdited(QString)), this, SLOT(OnSuggestDst(QString)));

	connect(m_ui->FromEdit, SIGNAL(returnPressed()), this, SLOT(on_SearchButton_pressed()));
	connect(m_ui->ToEdit, SIGNAL(returnPressed()), this, SLOT(on_SearchButton_pressed()));

	m_Completer = 0;
}

QueryForm::~QueryForm() {
    delete m_ui;
	m_Completer->deleteLater();
}

QString QueryForm::From() {
	return m_ui->FromEdit->text();
}

QString QueryForm::To() {
	return m_ui->ToEdit->text();
}

QString QueryForm::Beautifulize(const QString & Text) {
	QString Str1, Str2;
	foreach (QString SubStr, Text.split("-", QString::SkipEmptyParts)) {
		Str1 += (SubStr.left(1).toUpper()) + (SubStr.right(SubStr.length() - 1).toLower()) + "-";
	}
	Str1 = Str1.left(Str1.length() - 1);
	foreach (QString SubStr, Str1.split(" ", QString::SkipEmptyParts)) {
		Str2 += (SubStr.left(1).toUpper()) + (SubStr.right(SubStr.length() - 1)) + " ";
	}
	return Str2.left(Str2.length() - 1);
}

void QueryForm::on_SearchButton_pressed() {
	// cancel
	jinn.Cancel();

	m_Map.clear();
	emit Query(
			m_ui->FromEdit->text(),
			m_ui->ToEdit->text(),
			m_ui->DateTimeEditStart->date().toString("dd.MM"),
			m_ui->DateTimeEditEnd->date().toString("dd.MM")
			);
	setEnabled(false);

	QueryFormSettings.setValue("QueryForm/From", m_ui->FromEdit->text());
	QueryFormSettings.setValue("QueryForm/To", m_ui->ToEdit->text());
}

void QueryForm::OnSuggestSrc(QString From) {
	Suggest(From, m_ui->FromEdit);
}

void QueryForm::OnSuggestDst(QString To) {
	Suggest(To, m_ui->ToEdit);
}

void QueryForm::Suggest(QString Text, QLineEdit * Edit) {
	if (Text.length() < 3) {
		return;
	}

	// cancel
	jinn.Cancel();
/*
	int Id = rzd::Request(
			rzd::PassHost(),
			rzd::Query("StationSuggest") + QByteArray(Text.toUtf8()),
			rzd::Text,
			rzd::Utf8,
			this,
			SLOT(OnSuggestPageFinished(QString, int,bool)));
*/
	int Id = jinn.Request(
			"http://" + rzd::PassHost() + rzd::Query("StationSuggest") + Text,
			HtmlGenie::ContentTypeText(),
			this,
			SLOT(OnSuggestPageFinished(HtmlResponse *,int,bool))
			);

	m_Map.insert(Id, Edit);
}

void QueryForm::OnSuggestPageFinished(HtmlResponse * Response, int Id, bool _Error) {
	qDebug() << __FUNCTION__;

	if (_Error) {
		qDebug() << "OnSuggestPageFinished with error, restart";
		return;
	}

	QStringList Table;
	HtmlElementPars _pars;
	_pars.Name = "stations";

	HtmlSelectorDataList _select_list = Response->Selectors(_pars);
	if (_select_list.size() > 0) {
		foreach (const HtmlOptionData & _option, _select_list.at(0).Options) {
			Table << _option.Text.simplified().replace('\n', "").replace('\r', "");
		}
	}

/*
	if (Response.contains("onDblClick=\"return do_select_station()\">") == false) {
		qDebug() << "OnSuggestPageFinished" << "Wrong page";
		return;
	}

	Response = Response.split("onDblClick=\"return do_select_station()\">").at(1);
	Response = Response.split("</select>").at(0);

	QStringList Table;
	foreach(QString Line, Response.split("\n", QString::SkipEmptyParts)) {
		if (Line.contains("<option") == true) {
			Line = Line.replace('\n', "").replace('\r', "").simplified();
			if (Line.contains("]")) {
				Line = Line.split("]").at(1);
			}
			if (Line.contains("|")) {
				Line = Line.split("|").at(0);
			}
			if (Line.isEmpty() == false) {
				Table << Line;
			}
		}
	}
*/
	if (m_Map.contains(Id)) {
		QLineEdit * Edit = m_Map.value(Id);
		m_Map.remove(Id);
		if (Edit->hasFocus() == false) {
			return;
		}

		if (m_Completer) {
			m_Completer->deleteLater();
		}
		m_Completer = new SuggestCompletion(Edit);
		m_Completer->showCompletion(Table);
	}

}

void QueryForm::on_pushButton_pressed() {
	QString To = m_ui->ToEdit->text();
	m_ui->ToEdit->setText(m_ui->FromEdit->text());
	m_ui->FromEdit->setText(To);
}

void QueryForm::on_DateTimeEditStart_dateTimeChanged(QDateTime date) {
	if (date > m_ui->DateTimeEditEnd->dateTime()) {
		m_ui->DateTimeEditEnd->setDateTime(date);
	}
}

void QueryForm::on_DateTimeEditEnd_dateTimeChanged(QDateTime date) {
	if (date < m_ui->DateTimeEditStart->dateTime()) {
		m_ui->DateTimeEditEnd->setDateTime(m_ui->DateTimeEditStart->dateTime());
	}
}
